<template>
  <div>
    <div class="modal-body">
      <div class="steps">
        <a-steps size="small" :current="0" :status="'process'">
          <a-step :title="$t('languages.Apps.UploadFile')"></a-step>
          <a-step :title="$t('languages.Apps.VerifyFile')"></a-step>
          <a-step :title="$t('languages.Apps.Import')"></a-step>
        </a-steps>
      </div>

      <div class="data-upload">
        <div class="folders">
          <div class="upload-left">{{ $t('languages.Apps.Catalogues') }}:</div>
          <div class="upload-right">
            <a-select
              style="width: 100%"
              v-model="folderId"
              @change="handleFolderChange"
            >
              <a-select-option
                v-for="(floder, index) in tree"
                v-model="floder.id"
                :key="index"
              >{{ getLangName(floder) }}</a-select-option>
            </a-select>
          </div>
          <div class="clearfix"></div>
        </div>
        <div  class="folders">
          <div class="upload-left">{{ $t('languages.Apps.UploadLocalFile') }}:</div>
          <div class="upload-right">
            <div class="upload-dragger">
              <a-upload-dragger
                :multiple="false"
                :accept="accept"
                :fileList="fileList"
                :action="action"
                :headers="header"
                :beforeUpload="beforeUpload"
                @change="handleChange"
                @remove="removeFile"
              >
                <div class="tip">
                  <i class="aufontAll h-icon-all-export_o"></i>
                  {{ $t('languages.Apps.ClickOrDragFile') }}
                  <div class="upload-tip">{{ $t('languages.Apps.SupportXMLFile') }}</div>
                </div>
              </a-upload-dragger>
              <!-- <div class="upload-tip">{{ $t('languages.Apps.SupportXMLFile') }}</div> -->
            </div>
          </div>
          <div class="clearfix"></div>
        </div>
      </div>
    </div>

    <div class="modal-footer">
      <!-- 下一步 -->
        <a-button type="primary" :disabled="nextDisabled" @click="nextStep">{{
            $t('languages.Apps.NextStep')
          }}
        </a-button>
    </div>
  </div>
</template>

<script lang="ts">
import { LanguageTransform } from '@/utils';
import { listApi as Application } from '@cloudpivot/api';
import { Upload } from '@h3/antd-vue';
import {
  Component, Prop, Vue, Watch
} from 'vue-property-decorator';
import { namespace } from 'vuex-class';





const AppCenterModule = namespace('Apps/AppCenter');

const MenuModule = namespace('Apps/AppItem');

@Component({
  name: 'DataUpload',
  components: {
    AUpload: Upload
  }
})

export default class DataUpload extends Vue {
  @MenuModule.State('floders') floders: any;

  @MenuModule.State('menuId') menuId: any;

  @AppCenterModule.State('appInfo') appDetails: any;

  @MenuModule.State('appInfo') appInfo: any;

  @MenuModule.Action('getFolders') getFolders: any;

  @Prop() accept!: any;

  @Prop() action!: any;

  defaultFolder: string = ''; // 默认目录

  fileList:Array<any> = []; // 文件列表

  folderId:string = '';

  nextDisabled: boolean = true; // 下一步按钮状态

  fileName: string = ''


  mounted() {
    const promise = new Promise((resolve: (value: any) => void, reject) => {
      resolve(this.getFolders(this.appInfo));
    });
    promise.then(() => {
      if (this.menuId) {
        const id = this.floders.filter(val => val.id === this.menuId);
        if (id.length === 0) {
          this.defaultFolder = this.appDetails.id;
        } else {
          this.defaultFolder = this.menuId;
        }

      } else {
        this.defaultFolder = this.appDetails.id;
      }
      this.folderId = this.defaultFolder;
    });
  }

  get disabled() {
    return this.fileList.length > 0;
  }

  get header() {
    const token = localStorage.getItem('token');
    return {
      Authorization: `Bearer ${token}`
    };
  }

  get tree(){
    return this.allGroup(this.floders);
  }

  allGroup(res: any) {
    let retData = [] as any;
    let _helper = (data: any) => {
      if (!data) return;
      data.forEach((item: any) => {
        retData.push(item);
        if (Array.isArray(item.children)) {
          _helper(item.children);
        }
      });
    };
    _helper(res);
    return retData;
  }

  handleChange({ file, fileList }:any) {
    if (file.status !== 'uploading') {
      this.fileList = fileList;
    }

    // 上传完成逻辑
    if (file.status === 'done') {
      this.fileName = file.response;
    }

    if (file.status === 'removed') {
      Application.deleteTemporaryFile({fileName: file.response});
      this.fileName = ''
    }
  }

  // 删除文件
  removeFile(file:any) {
    this.fileList = [];
    this.fileName = ''
  }

  @Watch('fileName')
  watchFileName(fileName) {
    if(fileName !== '')
      this.nextDisabled = false
    else
      this.nextDisabled = true
  }

  /**
   * 文件上传前校验文件类型
   */
  beforeUpload(file:any) {
    this.fileList = [...this.fileList, file];
    this.fileList = this.fileList.slice(-1);

    const isZip = file.type.includes("xml");
      if (!isZip) {
       this.fileList.pop();
       this.$message.error("仅支持上传zip格式的文件");
       return false;
    }

    const types = this.accept.split(',');
    const fileType = file.name.substring(file.name.lastIndexOf('.'));
    return types.indexOf(fileType) > -1;
  }

  /**
   * 选择文件夹
   */
  handleFolderChange(folder:string) {
    console.log(folder, 'folder');
    this.folderId = folder
  }

  /**
   * 获取当前语言对应展示名
   */
  getLangName(item:any) {
    return LanguageTransform.getLang(item.name, item.name_i18n);
  }

  nextStep() {
    this.$emit('nextStep', {
      fileName: this.fileName,
      folderId: this.folderId,
    })
  }
}
</script>

<style lang="less" scoped>
  .modal-body{
    margin: auto 24px;
    .steps{
      width: 50%;
      margin: 30px auto;
    }
  }
  .data-upload {
    margin: 24px auto;
    & .folders {
      margin-top:20px;
    }
    & .upload-left {
      width: 98px;
      float: left;
      vertical-align: middle;
      height: 22px;
      line-height: 22px;
      margin-right: 2px;
    }
    & .upload-right {
      width: 490px;
      float: left;
      vertical-align: middle;
      & .ant-upload-list {
        margin-top: 20px;
      }
      & .upload-dragger {
        display: block;
        position: relative;
        & .ant-upload.ant-upload-drag {
          background:rgba(255,255,255,1);
          border:1px solid rgba(217,217,217,1);
        }
        & .ant-upload.ant-upload-drag .ant-upload-drag-container div {
          text-align: center;
          height:28px;
          line-height: 28px;
          color: rgba(0, 0, 0, 0.65);
        }
        & .ant-upload.ant-upload-drag .ant-upload-btn {
          padding: 0;
        }
      }
    }
    & .upload-tip {      
      position: absolute;
      bottom: -30px;
      left: 0;
      font-size: 12px;
      color: rgba(0, 0, 0, .45);
    }

    .clearfix {
      clear: both;
    }
  }
</style>

<style lang="less" scoped>
  .data-upload {
    /deep/ .ant-upload-list-item-info .anticon-paper-clip {
      top: 3px;
    }
    /deep/ .ant-upload-list-item-info{
      margin-top: 30px;
    }
  }
</style>
